package pannel.recipe;

import system.BasePage;
import pannel.user.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

public class FavoriteListPage extends BasePage {
    private JPanel cardsPanel;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private RecipeDao recipeDao;
    private List<Recipe> recipeList = new ArrayList<>();
    private int totalRecords = 0;
    
    // 添加常量
    private static final int CARDS_PER_ROW = 3;
    private static final double CARD_RATIO = 0.45;
    private static final double IMAGE_RATIO = 0.6;
    private static final int CARD_GAP = 15;
    private static final int IMAGE_SIZE = 200;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public FavoriteListPage(User user) {
        super(user);
        this.recipeDao = new RecipeDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("我的收藏");
        setupContent();
        refreshCards();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());

        // 创建卡片容器面板
        initializeCardsPanel();

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        paginationPanel.setBackground(Color.WHITE);
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshCards();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshCards();
            }
        });

        // 添加窗口大小变化监听器
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                refreshCards();
            }
        });

        contentArea.add(cardsPanel, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void initializeCardsPanel() {
        cardsPanel = new JPanel();
        // 使用GridLayout，设置合适的间距
        cardsPanel.setLayout(new GridLayout(0, 2, 15, 15));
        cardsPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        cardsPanel.setBackground(Color.WHITE);
        
        // 滚动面板设置
        JScrollPane scrollPane = new JScrollPane(cardsPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setBorder(null);
        
        contentArea.add(scrollPane, BorderLayout.CENTER);
    }

    private void refreshCards() {
        SwingUtilities.invokeLater(() -> {
            try {
                recipeList = recipeDao.getFavoriteRecipes(getCurrentUser().getId(), currentPage, pageSize);
                totalRecords = recipeDao.getFavoriteTotalCount(getCurrentUser().getId());

                cardsPanel.removeAll();
                
                for (Recipe recipe : recipeList) {
                    cardsPanel.add(createRecipeCard(recipe));
                }

                updatePageInfo();
                
                // 重新计算布局
                cardsPanel.revalidate();
                cardsPanel.repaint();
                
                // 滚动到顶部并更新滚动条
                SwingUtilities.invokeLater(() -> {
                    Container parent = cardsPanel.getParent();
                    while (parent != null && !(parent instanceof JScrollPane)) {
                        parent = parent.getParent();
                    }
                    if (parent instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane) parent;
                        scrollPane.getVerticalScrollBar().setValue(0);
                        scrollPane.revalidate();
                        scrollPane.repaint();
                    }
                });
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取收藏数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }

    private JPanel createRecipeCard(Recipe recipe) {
        // 主卡片容器
        JPanel card = new JPanel();
        card.setLayout(new BorderLayout(10, 10));
        card.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.LIGHT_GRAY),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));
        card.setBackground(Color.WHITE);
        card.setPreferredSize(new Dimension(450, 200)); // 调整卡片大小

        // 左侧图片面板
        JPanel imagePanel = new JPanel();
        imagePanel.setBackground(Color.WHITE);
        imagePanel.setPreferredSize(new Dimension(150, 150));
        
        // 加载并缩放图片
        ImageIcon originalIcon = new ImageIcon(recipe.getImagePath());
        Image scaledImage = originalIcon.getImage().getScaledInstance(120, 120, Image.SCALE_SMOOTH);
        JLabel imageLabel = new JLabel(new ImageIcon(scaledImage));
        imagePanel.add(imageLabel);

        // 右侧信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBackground(Color.WHITE);

        // 菜谱名称
        JLabel nameLabel = new JLabel(recipe.getName());
        nameLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 分类信息
        JLabel categoryLabel = new JLabel("分类: " + recipe.getCategoryName());
        categoryLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        categoryLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 描述文本
        JTextArea descArea = new JTextArea();
        descArea.setText(recipe.getDescription());
        descArea.setWrapStyleWord(true);
        descArea.setLineWrap(true);
        descArea.setRows(3);
        descArea.setEditable(false);
        descArea.setBackground(Color.WHITE);
        descArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        descArea.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
        
        // 取消收藏按钮
        JButton unfavoriteButton = new JButton("取消收藏");
        unfavoriteButton.setForeground(new Color(220, 20, 60));
        unfavoriteButton.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // 按钮点击事件
        unfavoriteButton.addActionListener(e -> {
            int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要取消收藏这个菜谱吗？",
                "确认取消收藏",
                JOptionPane.YES_NO_OPTION
            );
            
            if (confirm == JOptionPane.YES_OPTION) {
                try {
                    if (recipeDao.removeFavorite(getCurrentUser().getId(), recipe.getId())) {
                        JOptionPane.showMessageDialog(this, "取消收藏成功！");
                        refreshCards();
                    } else {
                        JOptionPane.showMessageDialog(this, "取消收藏失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage());
                }
            }
        });

        // 组装信息面板
        infoPanel.add(nameLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(categoryLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(descArea);
        infoPanel.add(Box.createVerticalStrut(10));
        infoPanel.add(unfavoriteButton);

        // 组装主卡片
        card.add(imagePanel, BorderLayout.WEST);
        card.add(infoPanel, BorderLayout.CENTER);

        return card;
    }

    private ImageIcon createScaledImageIcon(String path, int width, int height) {
        if (path == null || path.isEmpty()) {
            return createDefaultIcon(width, height);
        }
        try {
            ImageIcon originalIcon = new ImageIcon(path);
            Image image = originalIcon.getImage();
            return new ImageIcon(image.getScaledInstance(width, height, Image.SCALE_SMOOTH));
        } catch (Exception e) {
            return createDefaultIcon(width, height);
        }
    }

    private ImageIcon createDefaultIcon(int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, width, height);
        g2d.dispose();
        return new ImageIcon(image);
    }

    // 添加WrapLayout内部类
    private class WrapLayout extends FlowLayout {
        public WrapLayout(int align, int hgap, int vgap) {
            super(align, hgap, vgap);
        }

        @Override
        public Dimension preferredLayoutSize(Container target) {
            return layoutSize(target, true);
        }

        @Override
        public Dimension minimumLayoutSize(Container target) {
            return layoutSize(target, false);
        }

        private Dimension layoutSize(Container target, boolean preferred) {
            synchronized (target.getTreeLock()) {
                int targetWidth = target.getWidth();
                if (targetWidth == 0) {
                    targetWidth = Integer.MAX_VALUE;
                }

                int hgap = getHgap();
                int vgap = getVgap();
                Insets insets = target.getInsets();
                int maxWidth = targetWidth - (insets.left + insets.right);
                int x = insets.left;
                int y = insets.top;
                int rowHeight = 0;
                int rowWidth = 0;
                int numInRow = 0;

                int nmembers = target.getComponentCount();
                for (int i = 0; i < nmembers; i++) {
                    Component m = target.getComponent(i);
                    if (m.isVisible()) {
                        Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
                        
                        // 检查是否需要换行
                        if (numInRow >= CARDS_PER_ROW || (x > insets.left && x + d.width > maxWidth)) {
                            x = insets.left;
                            y += vgap + rowHeight;
                            rowHeight = 0;
                            numInRow = 0;
                        }
                        
                        // 更新位置和高度
                        if (x > insets.left) {
                            x += hgap;
                        }
                        x += d.width;
                        rowWidth = Math.max(rowWidth, x - insets.left);
                        rowHeight = Math.max(rowHeight, d.height);
                        numInRow++;
                    }
                }
                
                // 添加最后一行的高度
                if (rowHeight > 0) {
                    y += rowHeight + vgap;
                }

                return new Dimension(targetWidth, y);
            }
        }
    }
} 